package com.kaikeba.t31.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.kaikeba.t31.admin.po.AdminRole;
import com.kaikeba.t31.admin.po.AdminRoleMenu;
import com.kaikeba.t31.admin.po.AdminRoleUser;
import com.kaikeba.t31.admin.vo.AdminRoleVo;
import com.kaikeba.t31.core.service.impl.CrudServiceImpl;
import com.kaikeba.t31.dao.AdminRoleMapper;
import com.kaikeba.t31.service.AdminRoleMenuService;
import com.kaikeba.t31.service.AdminRoleService;
import com.kaikeba.t31.service.AdminRoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yumingzhi
 * @since 2021-11-14
 */
@Service
public class AdminRoleServiceImpl extends CrudServiceImpl<AdminRole> implements AdminRoleService {

    @Resource
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private AdminRoleUserService adminRoleUserService;
    @Autowired
    private AdminRoleMenuService adminRoleMenuService;
    @Override
    public void saveRole(AdminRoleVo adminRoleVo) {
        // 1、判断角色是否存在，更新角色信息
        AdminRole adminRole = new AdminRole();
        adminRole.setId(adminRoleVo.getId());
        adminRole.setComment(adminRoleVo.getComment());
        adminRole.setTitle(adminRoleVo.getTitle());
        adminRole.setName(adminRoleVo.getName());
        saveOrUpdate(adminRole);
        System.out.println("a");
        System.out.println(adminRole.getId());
        // 2、菜单信息和用户信息，先删除，在增加
        adminRoleUserService.deleteByRole(adminRole.getId());
        List<Long> userIds = adminRoleVo.getUserIds();
        if (CollectionUtils.isNotEmpty(userIds)) {
            List<AdminRoleUser> adminRoleUsers = Lists.newArrayListWithCapacity(userIds.size());
            for (Long userId :userIds){
                AdminRoleUser adminRoleUser = new AdminRoleUser();
                adminRoleUser.setRoleId(adminRole.getId());
                adminRoleUser.setUserId(userId);
                adminRoleUsers.add(adminRoleUser);
            }
            adminRoleUserService.saveBatch(adminRoleUsers);
        }

        adminRoleMenuService.deleteByRole(adminRole.getId());
        List<Long> menuIds = adminRoleVo.getPermissionIds();
        if (CollectionUtils.isNotEmpty(userIds)) {
            List<AdminRoleMenu> adminRoleMenus = Lists.newArrayListWithCapacity(userIds.size());
            for (Long menuId :menuIds){
                AdminRoleMenu adminRoleMenu = new AdminRoleMenu();
                adminRoleMenu.setRoleId(adminRole.getId());
                adminRoleMenu.setMenuId(menuId);
                adminRoleMenus.add(adminRoleMenu);
            }
            adminRoleMenuService.saveBatch(adminRoleMenus);
        }

    }
}
